<html lang="en-US">

<head>
    
<title>用 Go map 要注意这个细节，避免依赖他！ - 花落雨忧</title>

<meta property="og:title" content="用 Go map 要注意这个细节，避免依赖他！ - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
最近又有同学问我这个日经话题，想转他文章时，结果发现我的公众号竟然没有发过，因此今天我再唠叨两句，好让大家避开这个 “坑”。
有的小伙伴没留意过 Go map 输出、遍历顺序，以为它是稳定的有序的，会在业务程序中直接依赖这个结果集顺序，结果栽了个大跟头，吃了线上 BUG。
有的小伙伴知道是无序的，但却不知道为什么,有的却理解错误？
今天通过本文，我们将揭开 for range &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
最近又有同学问我这个日经话题，想转他文章时，结果发现我的公众号竟然没有发过，因此今天我再唠叨两句，好让大家避开这个 “坑”。
有的小伙伴没留意过 Go map 输出、遍历顺序，以为它是稳定的有序的，会在业务程序中直接依赖这个结果集顺序，结果栽了个大跟头，吃了线上 BUG。
有的小伙伴知道是无序的，但却不知道为什么,有的却理解错误？
今天通过本文，我们将揭开 for range &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/go-map-access/">用 Go map 要注意这个细节，避免依赖他！</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/09/12</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>最近又有同学问我这个日经话题，想转他文章时，结果发现我的公众号竟然没有发过，因此今天我再唠叨两句，好让大家避开这个 “坑”。</p>
<p>有的小伙伴没留意过 Go map 输出、遍历顺序，<strong>以为它是稳定的有序的，会在业务程序中直接依赖这个结果集顺序，结果栽了个大跟头</strong>，吃了线上 BUG。</p>
<p>有的小伙伴知道是无序的，但却不知道为什么,有的却理解错误？</p>
<p><img src="http://wx2.sinaimg.cn/large/006fVPCvly1g1s1ah84k8j30k70dvaac.jpg" alt="奇怪的输出结果"></p>
<p>今天通过本文，我们将揭开 <code>for range map</code> 输出的 “神秘” 面纱，看看它内部实现到底是怎么样的，顺序到底是怎么样？</p>
<p>开始吸鱼之路。</p>
<h2 id="前言">前言</h2>
<p>例子如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">m</span> <span style="color:#f92672">:=</span> make(<span style="color:#66d9ef">map</span>[<span style="color:#66d9ef">int32</span>]<span style="color:#66d9ef">string</span>)
	<span style="color:#a6e22e">m</span>[<span style="color:#ae81ff">0</span>] = <span style="color:#e6db74">&#34;EDDYCJY1&#34;</span>
	<span style="color:#a6e22e">m</span>[<span style="color:#ae81ff">1</span>] = <span style="color:#e6db74">&#34;EDDYCJY2&#34;</span>
	<span style="color:#a6e22e">m</span>[<span style="color:#ae81ff">2</span>] = <span style="color:#e6db74">&#34;EDDYCJY3&#34;</span>
	<span style="color:#a6e22e">m</span>[<span style="color:#ae81ff">3</span>] = <span style="color:#e6db74">&#34;EDDYCJY4&#34;</span>
	<span style="color:#a6e22e">m</span>[<span style="color:#ae81ff">4</span>] = <span style="color:#e6db74">&#34;EDDYCJY5&#34;</span>

	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">k</span>, <span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">m</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;k: %v, v: %v&#34;</span>, <span style="color:#a6e22e">k</span>, <span style="color:#a6e22e">v</span>)
	}
}
</code></pre></div><p>假设运行这段代码，输出的结果是怎么样？是有序，还是无序输出呢？</p>
<pre><code>k: 3, v: EDDYCJY4
k: 4, v: EDDYCJY5
k: 0, v: EDDYCJY1
k: 1, v: EDDYCJY2
k: 2, v: EDDYCJY3
</code></pre><p>从输出结果上来讲，是非固定顺序输出的，也就是每次都不一样。但这是为什么呢？</p>
<p>首先<strong>建议你先自己想想原因</strong>。其次我在面试时听过一些说法。有人说因为是哈希的所以就是无（乱）序等等说法。当时我是有点 ？？？</p>
<p>这也是这篇文章出现的原因，希望大家可以一起研讨一下，理清这个问题 ：）</p>
<h2 id="看一下汇编">看一下汇编</h2>
<pre><code>    ...
	0x009b 00155 (main.go:11)	LEAQ	type.map[int32]string(SB), AX
	0x00a2 00162 (main.go:11)	PCDATA	$2, $0
	0x00a2 00162 (main.go:11)	MOVQ	AX, (SP)
	0x00a6 00166 (main.go:11)	PCDATA	$2, $2
	0x00a6 00166 (main.go:11)	LEAQ	&quot;&quot;..autotmp_3+24(SP), AX
	0x00ab 00171 (main.go:11)	PCDATA	$2, $0
	0x00ab 00171 (main.go:11)	MOVQ	AX, 8(SP)
	0x00b0 00176 (main.go:11)	PCDATA	$2, $2
	0x00b0 00176 (main.go:11)	LEAQ	&quot;&quot;..autotmp_2+72(SP), AX
	0x00b5 00181 (main.go:11)	PCDATA	$2, $0
	0x00b5 00181 (main.go:11)	MOVQ	AX, 16(SP)
	0x00ba 00186 (main.go:11)	CALL	runtime.mapiterinit(SB)
	0x00bf 00191 (main.go:11)	JMP	207
	0x00c1 00193 (main.go:11)	PCDATA	$2, $2
	0x00c1 00193 (main.go:11)	LEAQ	&quot;&quot;..autotmp_2+72(SP), AX
	0x00c6 00198 (main.go:11)	PCDATA	$2, $0
	0x00c6 00198 (main.go:11)	MOVQ	AX, (SP)
	0x00ca 00202 (main.go:11)	CALL	runtime.mapiternext(SB)
	0x00cf 00207 (main.go:11)	CMPQ	&quot;&quot;..autotmp_2+72(SP), $0
	0x00d5 00213 (main.go:11)	JNE	193
	...
</code></pre><p>我们大致看一下整体过程，重点处理 Go map 循环迭代的是两个 runtime 方法，如下：</p>
<ul>
<li>runtime.mapiterinit</li>
<li>runtime.mapiternext</li>
</ul>
<p>但你可能会想，明明用的是 <code>for range</code> 进行循环迭代，怎么出现了这两个函数，怎么回事？</p>
<h2 id="看一下转换后">看一下转换后</h2>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">var</span> <span style="color:#a6e22e">hiter</span> <span style="color:#a6e22e">map_iteration_struct</span>
<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">mapiterinit</span>(<span style="color:#66d9ef">type</span>, <span style="color:#66d9ef">range</span>, <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">hiter</span>); <span style="color:#a6e22e">hiter</span>.<span style="color:#a6e22e">key</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span>; <span style="color:#a6e22e">mapiternext</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">hiter</span>) {
    <span style="color:#a6e22e">index_temp</span> = <span style="color:#f92672">*</span><span style="color:#a6e22e">hiter</span>.<span style="color:#a6e22e">key</span>
    <span style="color:#a6e22e">value_temp</span> = <span style="color:#f92672">*</span><span style="color:#a6e22e">hiter</span>.<span style="color:#a6e22e">val</span>
    <span style="color:#a6e22e">index</span> = <span style="color:#a6e22e">index_temp</span>
    <span style="color:#a6e22e">value</span> = <span style="color:#a6e22e">value_temp</span>
    <span style="color:#a6e22e">original</span> <span style="color:#a6e22e">body</span>
}
</code></pre></div><p>实际上编译器对于 slice 和 map 的循环迭代有不同的实现方式，并不是 <code>for</code> 一扔就完事了，还做了一些附加动作进行处理。而上述代码就是 <code>for range map</code> 在编译器展开后的伪实现</p>
<h2 id="看一下源码">看一下源码</h2>
<h3 id="runtimemapiterinit">runtime.mapiterinit</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">mapiterinit</span>(<span style="color:#a6e22e">t</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">maptype</span>, <span style="color:#a6e22e">h</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">hmap</span>, <span style="color:#a6e22e">it</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">hiter</span>) {
	<span style="color:#f92672">...</span>
	<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">t</span> = <span style="color:#a6e22e">t</span>
	<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">h</span> = <span style="color:#a6e22e">h</span>
	<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">B</span> = <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">B</span>
	<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">buckets</span> = <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">buckets</span>
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">bucket</span>.<span style="color:#a6e22e">kind</span><span style="color:#f92672">&amp;</span><span style="color:#a6e22e">kindNoPointers</span> <span style="color:#f92672">!=</span> <span style="color:#ae81ff">0</span> {
		<span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">createOverflow</span>()
		<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">overflow</span> = <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">extra</span>.<span style="color:#a6e22e">overflow</span>
		<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">oldoverflow</span> = <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">extra</span>.<span style="color:#a6e22e">oldoverflow</span>
	}

	<span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> uintptr(<span style="color:#a6e22e">fastrand</span>())
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">B</span> &gt; <span style="color:#ae81ff">31</span><span style="color:#f92672">-</span><span style="color:#a6e22e">bucketCntBits</span> {
		<span style="color:#a6e22e">r</span> <span style="color:#f92672">+=</span> uintptr(<span style="color:#a6e22e">fastrand</span>()) <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">31</span>
	}
	<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">startBucket</span> = <span style="color:#a6e22e">r</span> <span style="color:#f92672">&amp;</span> <span style="color:#a6e22e">bucketMask</span>(<span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">B</span>)
	<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">offset</span> = uint8(<span style="color:#a6e22e">r</span> <span style="color:#f92672">&gt;&gt;</span> <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">B</span> <span style="color:#f92672">&amp;</span> (<span style="color:#a6e22e">bucketCnt</span> <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>))
	<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">bucket</span> = <span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">startBucket</span>
    <span style="color:#f92672">...</span>

	<span style="color:#a6e22e">mapiternext</span>(<span style="color:#a6e22e">it</span>)
}
</code></pre></div><p>通过对 <code>mapiterinit</code> 方法阅读，可得知其主要用途是在 map 进行遍历迭代时<strong>进行初始化动作</strong>。共有三个形参，用于读取当前哈希表的类型信息、当前哈希表的存储信息和当前遍历迭代的数据</p>
<h4 id="为什么">为什么</h4>
<p>咱们关注到源码中 <code>fastrand</code> 的部分，这个方法名，是不是迷之眼熟。没错，它是一个生成随机数的方法。再看看上下文：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">...</span>
<span style="color:#75715e">// decide where to start
</span><span style="color:#75715e"></span><span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> uintptr(<span style="color:#a6e22e">fastrand</span>())
<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">B</span> &gt; <span style="color:#ae81ff">31</span><span style="color:#f92672">-</span><span style="color:#a6e22e">bucketCntBits</span> {
	<span style="color:#a6e22e">r</span> <span style="color:#f92672">+=</span> uintptr(<span style="color:#a6e22e">fastrand</span>()) <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">31</span>
}
<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">startBucket</span> = <span style="color:#a6e22e">r</span> <span style="color:#f92672">&amp;</span> <span style="color:#a6e22e">bucketMask</span>(<span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">B</span>)
<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">offset</span> = uint8(<span style="color:#a6e22e">r</span> <span style="color:#f92672">&gt;&gt;</span> <span style="color:#a6e22e">h</span>.<span style="color:#a6e22e">B</span> <span style="color:#f92672">&amp;</span> (<span style="color:#a6e22e">bucketCnt</span> <span style="color:#f92672">-</span> <span style="color:#ae81ff">1</span>))

<span style="color:#75715e">// iterator state
</span><span style="color:#75715e"></span><span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">bucket</span> = <span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">startBucket</span>
</code></pre></div><p>在这段代码中，它生成了随机数。用于决定从哪里开始循环迭代。更具体的话就是根据随机数，选择一个桶位置作为起始点进行遍历迭代</p>
<p>因此每次重新 <code>for range map</code>，你见到的结果都是不一样的。那是因为它的起始位置根本就不固定！</p>
<h3 id="runtimemapiternext">runtime.mapiternext</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">mapiternext</span>(<span style="color:#a6e22e">it</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">hiter</span>) {
    <span style="color:#f92672">...</span>
    <span style="color:#66d9ef">for</span> ; <span style="color:#a6e22e">i</span> &lt; <span style="color:#a6e22e">bucketCnt</span>; <span style="color:#a6e22e">i</span><span style="color:#f92672">++</span> {
		<span style="color:#f92672">...</span>
		<span style="color:#a6e22e">k</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Pointer</span>(<span style="color:#a6e22e">b</span>), <span style="color:#a6e22e">dataOffset</span><span style="color:#f92672">+</span>uintptr(<span style="color:#a6e22e">offi</span>)<span style="color:#f92672">*</span>uintptr(<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">keysize</span>))
		<span style="color:#a6e22e">v</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">add</span>(<span style="color:#a6e22e">unsafe</span>.<span style="color:#a6e22e">Pointer</span>(<span style="color:#a6e22e">b</span>), <span style="color:#a6e22e">dataOffset</span><span style="color:#f92672">+</span><span style="color:#a6e22e">bucketCnt</span><span style="color:#f92672">*</span>uintptr(<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">keysize</span>)<span style="color:#f92672">+</span>uintptr(<span style="color:#a6e22e">offi</span>)<span style="color:#f92672">*</span>uintptr(<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">valuesize</span>))
		<span style="color:#f92672">...</span>
		<span style="color:#66d9ef">if</span> (<span style="color:#a6e22e">b</span>.<span style="color:#a6e22e">tophash</span>[<span style="color:#a6e22e">offi</span>] <span style="color:#f92672">!=</span> <span style="color:#a6e22e">evacuatedX</span> <span style="color:#f92672">&amp;&amp;</span> <span style="color:#a6e22e">b</span>.<span style="color:#a6e22e">tophash</span>[<span style="color:#a6e22e">offi</span>] <span style="color:#f92672">!=</span> <span style="color:#a6e22e">evacuatedY</span>) <span style="color:#f92672">||</span>
			!(<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">reflexivekey</span> <span style="color:#f92672">||</span> <span style="color:#a6e22e">alg</span>.<span style="color:#a6e22e">equal</span>(<span style="color:#a6e22e">k</span>, <span style="color:#a6e22e">k</span>)) {
			<span style="color:#f92672">...</span>
			<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">key</span> = <span style="color:#a6e22e">k</span>
			<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">value</span> = <span style="color:#a6e22e">v</span>
		} <span style="color:#66d9ef">else</span> {
			<span style="color:#a6e22e">rk</span>, <span style="color:#a6e22e">rv</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">mapaccessK</span>(<span style="color:#a6e22e">t</span>, <span style="color:#a6e22e">h</span>, <span style="color:#a6e22e">k</span>)
			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">rk</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span> {
				<span style="color:#66d9ef">continue</span> <span style="color:#75715e">// key has been deleted
</span><span style="color:#75715e"></span>			}
			<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">key</span> = <span style="color:#a6e22e">rk</span>
			<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">value</span> = <span style="color:#a6e22e">rv</span>
		}
		<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">bucket</span> = <span style="color:#a6e22e">bucket</span>
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">bptr</span> <span style="color:#f92672">!=</span> <span style="color:#a6e22e">b</span> {
			<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">bptr</span> = <span style="color:#a6e22e">b</span>
		}
		<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">i</span> = <span style="color:#a6e22e">i</span> <span style="color:#f92672">+</span> <span style="color:#ae81ff">1</span>
		<span style="color:#a6e22e">it</span>.<span style="color:#a6e22e">checkBucket</span> = <span style="color:#a6e22e">checkBucket</span>
		<span style="color:#66d9ef">return</span>
	}
	<span style="color:#a6e22e">b</span> = <span style="color:#a6e22e">b</span>.<span style="color:#a6e22e">overflow</span>(<span style="color:#a6e22e">t</span>)
	<span style="color:#a6e22e">i</span> = <span style="color:#ae81ff">0</span>
	<span style="color:#66d9ef">goto</span> <span style="color:#a6e22e">next</span>
}
</code></pre></div><p>在上小节中，咱们已经选定了起始桶的位置。接下来就是通过 <code>mapiternext</code> 进行<strong>具体的循环遍历动作</strong>。该方法主要涉及如下：</p>
<ul>
<li>从已选定的桶中开始进行遍历，寻找桶中的下一个元素进行处理</li>
<li>如果桶已经遍历完，则对溢出桶 <code>overflow buckets</code> 进行遍历处理</li>
</ul>
<p>通过对本方法的阅读，可得知其对 buckets 的<strong>遍历规则</strong>以及对于扩容的一些处理（这不是本文重点。因此没有具体展开）</p>
<h2 id="总结">总结</h2>
<p>在本文开始，咱们先提出核心讨论点：“为什么 Go map 遍历输出是不固定顺序？”。</p>
<p>经过这一番分析，原因也很简单明了。就是 <code>for range map</code> 在开始处理循环逻辑的时候，就做了随机播种&hellip;</p>
<p>你想问为什么要这么做？</p>
<p>当然是官方有意为之，因为 Go 在早期（1.0）的时候，虽是稳定迭代的，但从结果来讲，其实是无法保证每个 Go 版本迭代遍历规则都是一样的。而这将会导致可移植性问题。</p>
<p>因此，改之。也请不要依赖&hellip;</p>
<h2 id="参考">参考</h2>
<ul>
<li><a href="https://blog.golang.org/go-maps-in-action">Go maps in action</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-errors-boom/">生产环境遇到一个 Go 问题，整组人都懵逼了...</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gmp-why-p/">经典面试题：你觉得 Go 在什么时候会抢占 P？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-empty-struct/">用 Go struct 不能犯的一个低级错误！</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/go-bootstrap0/">详解 Go 程序的启动流程，你知道 g0，m0 是什么吗？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/goroutine-leak/">跟面试官聊 Goroutine 泄露的 6 种方法，真刺激！</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/go-errors-boom/"
                                                    rel="prev">生产环境遇到一个 Go 问题，整组人都懵逼了...</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/go-standards/">上帝视角看 “Go 项目标准布局” 之争</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>